import axios from "axios";

import store from "@/store";
import router from "@/router";
import { Message } from "element-ui";

const request = axios.create({
  baseURL: "https://likede2-admin.itheima.net/likede",
  timeout: 5000,
});

request.interceptors.request.use(
  (config) => {
    const token = store.state.user.token;
    config.headers.Authorization = token;
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

request.interceptors.response.use(
  (response) => {
    // console.log(response);
    if (response.config.url === "/api/user-service/user/login") {
      if (response.data.success) {
        return response.data;
      } else {
        Message.error(response.data.msg);
        return Promise.reject(new Error(response.data.msg));
      }
    }
    return response;
  },
  (err) => {
    if (err.response.status === 401) {
      Message.error("登录状态有误，请重新登录");
      store.dispatch("user/logoutAction");
      router.push("/login");
    } else {
      Message.error(err.response.data.message);
    }
    return Promise.reject(err);
  }
);

export default request;
